#include <stdarg.h>
#include <string.h>
#include <stdio.h>
#include "logger.h"
#include "ls_hal_uart.h"

#define DEBUG_UART  MCU_UART2

void logger_init(void)
{
    hal_uart_init(DEBUG_UART);
}

void logger_output(int level, const char *tag, int line_num, const char *fmt, ...)
{
    char buf[LOG_BUF_SIZE] = {0};
    int idx = 0;
    va_list arg_list;

    if (level > LOG_LEVEL_VERBOSE) {
        return;
    }

    switch (level) {
        case LOG_LEVEL_ASSERT: {
            idx = sprintf(buf, "[ASR/%s] line(%d):", tag, line_num);
            break;
        }

        case LOG_LEVEL_ERROR: {
            idx = sprintf(buf, "[ERR/%s] line(%d):", tag, line_num);
            break;
        }

        case LOG_LEVEL_WARN: {
            idx = sprintf(buf, "[WAR/%s] line(%d):", tag, line_num);
            break;
        }

        case LOG_LEVEL_INFO: {
            idx = sprintf(buf, "[IFO/%s] line(%d):", tag, line_num);
            break;
        }

        case LOG_LEVEL_DEBUG: {
            idx = sprintf(buf, "[DBG/%s] line(%d):", tag, line_num);
            break;
        }

        case LOG_LEVEL_VERBOSE: {
            idx = sprintf(buf, "[VBS/%s] line(%d):", tag, line_num);
            break;
        }

        default: {
            break;
        }
    }

    va_start(arg_list, fmt);
    idx += vsnprintf(&buf[idx], LOG_BUF_SIZE - idx, fmt, arg_list);
    va_end(arg_list);

    hal_uart_write(DEBUG_UART, (mfU8_t *)buf, (mfU16_t)idx);
}

void logger_print(const char *fmt, ...)
{
    char buf[LOG_BUF_SIZE] = {0};
    int idx = 0;
    va_list arg_list;

    va_start(arg_list, fmt);
    idx += vsnprintf(&buf[idx], LOG_BUF_SIZE - idx, fmt, arg_list);
    va_end(arg_list);

    hal_uart_write(DEBUG_UART, (mfU8_t *)buf, (mfU16_t)idx);
}
